package savet.gui.tabelas.salario.editor;

import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.AbstractCellEditor;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import savet.gui.tabelas.AtributoCellEditor;

/**
 *
 * @author Adisson Marinho
 */
public abstract class AbstractButtonCellEditor extends AbstractCellEditor implements TableCellEditor {

    private JButton editar;
    private int countClick = 0;
    private Point lastCellSelected = null;
    private Object value = null;

    public AbstractButtonCellEditor() {
        editar = new JButton();
        editar.setBorderPainted(false);
        editar.setContentAreaFilled(false);
        editar.addActionListener(getOkAction());
    }

    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected,
            int row, int column) {
        this.value = value;
        verificaUltimaSelecao(row, column);
        return editar;
    }

    private void verificaUltimaSelecao(int row, int column) {
        final Point currentCell = new Point(row, column);
        if (lastCellSelected == null) {
            lastCellSelected = currentCell;
        }

        if (!lastCellSelected.equals(currentCell)) {
            lastCellSelected = currentCell;
            countClick = 0;
        }
    }

    public final Action getOkAction() {
        return new AbstractAction("Add") {

            public void actionPerformed(ActionEvent e) {
                countClick++;
                Thread t = new Thread(new Runnable() {

                    public void run() {
                        try {
                            Thread.sleep(450);
                            countClick = 0;
                        } catch (InterruptedException ex) {
                            Logger.getLogger(AtributoCellEditor.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                });
                t.start();
                if (countClick == 2) {
                    actionEditor(value);
                    countClick = 0;
                }
                fireEditingStopped();
            }
        };
    }

    public Object getCellEditorValue() {
        return value;
    }

    public abstract void actionEditor(Object value);
}
